<template>
  <PageContainer>
    <div class="generate-page">
      <div class="generate-header">
        <h1 class="page-title">文案生成</h1>
        <p class="page-description">为您的图片生成精彩文案</p>
      </div>
      
      <div class="generate-content">
        <div class="generate-sidebar">
          <ImageSelector
            :images="images"
            :loading="imagesLoading"
            :selected-image="selectedImage"
            @select="handleSelectImage"
            @load="handleLoadImages"
          />
        </div>
        
        <div class="generate-main">
          <TextGenerationPanel
            ref="textPanelRef"
            :selected-image="selectedImage"
            :generating="generating"
            @generate="handleGenerate"
            @select-text="handleSelectText"
          />
          
          <!-- 选中文案预览和操作面板 -->
          <div v-if="selectedText" class="action-panel">
            <div class="panel-header">
              <h3 class="panel-title">
                <el-icon><Operation /></el-icon>
                文案操作
              </h3>
            </div>
            
            <div class="selected-text-preview">
              <div class="preview-header">
                <span class="preview-title">选中的文案</span>
                <div class="preview-meta">
                  <el-tag :type="getContentTypeTagType(selectedText.contentType)" size="small">
                    {{ getContentTypeText(selectedText.contentType) }}
                  </el-tag>
                  <el-tag :type="getStyleTypeTagType(selectedText.styleType)" size="small">
                    {{ getStyleTypeText(selectedText.styleType) }}
                  </el-tag>
                </div>
              </div>
              <div class="preview-content">
                {{ selectedText.content }}
              </div>
            </div>
            
            <div class="action-buttons">
              <el-button 
                type="primary" 
                :icon="CopyDocument"
                @click="copySelectedText"
              >
                复制文案
              </el-button>
              <el-button 
                type="success" 
                :icon="DocumentAdd"
                @click="goToCompose"
              >
                图文组合
              </el-button>
              <el-button 
                type="info" 
                :icon="Share"
                @click="shareText"
              >
                分享文案
              </el-button>
              <el-button 
                type="warning" 
                :icon="Download"
                @click="exportText"
              >
                导出文案
              </el-button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 批量生成对话框 -->
      <el-dialog
        v-model="batchVisible"
        title="批量文案生成"
        width="600px"
        :before-close="handleCloseBatch"
      >
        <div class="batch-content">
          <div class="batch-images">
            <h4>选中的图片 ({{ batchImages.length }})</h4>
            <div class="batch-images-grid">
              <div
                v-for="image in batchImages"
                :key="image.id"
                class="batch-image-item"
              >
                <img :src="image.fileUrl" :alt="image.originalName" />
                <span class="batch-image-name">{{ image.originalName }}</span>
              </div>
            </div>
          </div>
          
          <div class="batch-config">
            <h4>生成配置</h4>
            <el-form :model="batchConfig" label-width="100px">
              <el-form-item label="文案类型">
                <el-radio-group v-model="batchConfig.contentType">
                  <el-radio-button label="SHORT">短句文案</el-radio-button>
                  <el-radio-button label="LONG">长句文案</el-radio-button>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="文案风格">
                <el-radio-group v-model="batchConfig.styleType">
                  <el-radio-button label="PROMOTIONAL">营销推广</el-radio-button>
                  <el-radio-button label="WARM">温馨暖心</el-radio-button>
                  <el-radio-button label="PROFESSIONAL">专业正式</el-radio-button>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="自定义提示">
                <el-input
                  v-model="batchConfig.customPrompt"
                  type="textarea"
                  :rows="3"
                  placeholder="可选：输入自定义提示词..."
                />
              </el-form-item>
            </el-form>
          </div>
        </div>
        
        <template #footer>
          <el-button @click="batchVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleBatchGenerate"
            :loading="batchGenerating"
          >
            {{ batchGenerating ? '生成中...' : '开始生成' }}
          </el-button>
        </template>
      </el-dialog>
      
      <!-- 批量生成进度对话框 -->
      <el-dialog
        v-model="batchProgressVisible"
        title="批量生成进度"
        width="500px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <div class="batch-progress">
          <div class="progress-header">
            <span>正在生成文案...</span>
            <span>{{ batchProgress.completed }}/{{ batchProgress.total }}</span>
          </div>
          
          <el-progress 
            :percentage="batchProgressPercentage" 
            :status="batchProgress.status"
          />
          
          <div class="progress-details">
            <div class="progress-item" 
                 v-for="item in batchProgress.items" 
                 :key="item.imageId"
                 :class="item.status"
            >
              <el-icon v-if="item.status === 'completed'"><Check /></el-icon>
              <el-icon v-else-if="item.status === 'error'"><Close /></el-icon>
              <el-icon v-else class="loading"><Loading /></el-icon>
              <span>{{ item.imageName }}</span>
              <span v-if="item.error" class="error-text">{{ item.error }}</span>
            </div>
          </div>
        </div>
        
        <template #footer>
          <el-button 
            @click="batchProgressVisible = false"
            :disabled="batchProgress.status === 'active'"
          >
            {{ batchProgress.status === 'active' ? '生成中...' : '完成' }}
          </el-button>
        </template>
      </el-dialog>
    </div>
  </PageContainer>
</template>

<script setup lang="ts">
/**
 * 文案生成页面组件
 * @author wangguiyou
 * @date 2025-01-27
 * @description 提供图片文案生成功能，支持单个和批量生成
 */
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Operation, CopyDocument, DocumentAdd, Share, Download,
  Check, Close, Loading
} from '@element-plus/icons-vue'
import PageContainer from '@/components/layout/PageContainer.vue'
import ImageSelector from '@/components/generate/ImageSelector.vue'
import TextGenerationPanel from '@/components/generate/TextGenerationPanel.vue'
import { imageApi } from '@/api/image'
import { textGenerationApi } from '@/api/ai'
import type { 
  ImageModel, 
  TextContentModel, 
  TextGenerationRequest 
} from '@/types'
import { copyToClipboard } from '@/utils'

const route = useRoute()
const router = useRouter()

// 响应式数据
const images = ref<ImageModel[]>([])
const imagesLoading = ref(false)
const selectedImage = ref<ImageModel | undefined>(undefined)
const selectedText = ref<TextContentModel | null>(null)
const generating = ref(false)
const textPanelRef = ref()

// 批量生成相关
const batchVisible = ref(false)
const batchImages = ref<ImageModel[]>([])
const batchGenerating = ref(false)
const batchProgressVisible = ref(false)

const batchConfig = reactive({
  contentType: 'SHORT' as 'SHORT' | 'LONG',
  styleType: 'PROMOTIONAL' as 'PROMOTIONAL' | 'WARM' | 'PROFESSIONAL',
  customPrompt: ''
})

const batchProgress = reactive({
  total: 0,
  completed: 0,
  status: 'active' as 'active' | 'success' | 'exception',
  items: [] as Array<{
    imageId: number
    imageName: string
    status: 'pending' | 'processing' | 'completed' | 'error'
    error?: string
  }>
})

// 计算属性
const batchProgressPercentage = computed(() => {
  if (batchProgress.total === 0) return 0
  return Math.round((batchProgress.completed / batchProgress.total) * 100)
})

/**
 * 加载图片列表
 */
const handleLoadImages = async (params: any = {}) => {
  try {
    imagesLoading.value = true
    
    const response = await imageApi.getImages({
      page: 0,
      size: 100,
      sortBy: 'createdAt',
      sortDir: 'desc',
      ...params
    })
    
    if (response.success && response.data) {
      images.value = response.data
    }
  } catch (error) {
    console.error('加载图片失败:', error)
    ElMessage.error('加载图片失败')
  } finally {
    imagesLoading.value = false
  }
}

/**
 * 选择图片
 */
const handleSelectImage = (image: ImageModel) => {
  selectedImage.value = image
  selectedText.value = null
}

/**
 * 生成文案
 */
const handleGenerate = async (config: TextGenerationRequest) => {
  if (!selectedImage.value) {
    ElMessage.warning('请先选择图片')
    return
  }
  
  try {
    generating.value = true
    
    const response = await textGenerationApi.generateText({
      ...config,
      imageId: selectedImage.value.id
    })
    
    if (response.success && response.data) {
      // 刷新文案面板
      if (textPanelRef.value?.refreshTexts) {
        textPanelRef.value.refreshTexts()
      }
      ElMessage.success('文案生成成功')
    } else {
      ElMessage.error(response.message || '文案生成失败')
    }
  } catch (error: any) {
    console.error('生成文案失败:', error)
    ElMessage.error(error.response?.data?.message || '文案生成失败')
  } finally {
    generating.value = false
  }
}

/**
 * 选择文案
 */
const handleSelectText = (text: TextContentModel) => {
  selectedText.value = text
}

/**
 * 复制选中的文案
 */
const copySelectedText = async () => {
  if (!selectedText.value) return
  
  try {
    await copyToClipboard(selectedText.value.content)
    ElMessage.success('文案已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

/**
 * 跳转到图文组合页面
 */
const goToCompose = () => {
  if (!selectedImage.value || !selectedText.value) return
  
  router.push({
    path: '/compose',
    query: {
      imageId: selectedImage.value.id,
      textId: selectedText.value.id
    }
  })
}

/**
 * 分享文案
 */
const shareText = async () => {
  if (!selectedText.value) return
  
  try {
    const shareContent = `${selectedText.value.content}\n\n来自AI图文管理系统`
    await copyToClipboard(shareContent)
    ElMessage.success('分享内容已复制到剪贴板')
  } catch (error) {
    ElMessage.error('分享失败')
  }
}

/**
 * 导出文案
 */
const exportText = () => {
  if (!selectedText.value) return
  
  const content = selectedText.value.content
  const blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `文案_${Date.now()}.txt`
  link.click()
  URL.revokeObjectURL(url)
  
  ElMessage.success('文案导出成功')
}

/**
 * 批量生成文案
 */
const handleBatchGenerate = async () => {
  if (batchImages.value.length === 0) return
  
  batchGenerating.value = true
  batchProgressVisible.value = true
  batchVisible.value = false
  
  // 初始化进度
  batchProgress.total = batchImages.value.length
  batchProgress.completed = 0
  batchProgress.status = 'active'
  batchProgress.items = batchImages.value.map(image => ({
    imageId: image.id,
    imageName: image.originalName,
    status: 'pending' as const
  }))
  
  // 逐个生成文案
  for (let i = 0; i < batchImages.value.length; i++) {
    const image = batchImages.value[i]
    const item = batchProgress.items[i]
    
    try {
      item.status = 'processing'
      
      const config: TextGenerationRequest = {
        imageId: image.id,
        contentType: batchConfig.contentType,
        styleType: batchConfig.styleType,
        customPrompt: batchConfig.customPrompt
      }
      
      const response = await textGenerationApi.generateText(config)
      
      if (response.success) {
        item.status = 'completed'
        batchProgress.completed++
      } else {
        item.status = 'error'
        item.error = '生成失败'
        batchProgress.completed++
      }
    } catch (error: any) {
      item.status = 'error'
      item.error = error.response?.data?.message || '生成失败'
      batchProgress.completed++
    }
  }
  
  batchProgress.status = 'success'
  batchGenerating.value = false
  
  ElMessage.success(`批量生成完成，成功生成 ${batchProgress.items.filter(item => item.status === 'completed').length} 条文案`)
}

/**
 * 关闭批量生成对话框
 */
const handleCloseBatch = () => {
  batchVisible.value = false
  batchImages.value = []
}

/**
 * 获取内容类型文本
 */
const getContentTypeText = (type: string) => {
  switch (type) {
    case 'SHORT': return '短句'
    case 'LONG': return '长句'
    default: return type
  }
}

/**
 * 获取内容类型标签类型
 */
const getContentTypeTagType = (type: string) => {
  switch (type) {
    case 'SHORT': return 'success'
    case 'LONG': return 'primary'
    default: return ''
  }
}

/**
 * 获取风格类型文本
 */
const getStyleTypeText = (type: string) => {
  switch (type) {
    case 'PROMOTIONAL': return '营销'
    case 'WARM': return '温馨'
    case 'PROFESSIONAL': return '专业'
    default: return type
  }
}

/**
 * 获取风格类型标签类型
 */
const getStyleTypeTagType = (type: string) => {
  switch (type) {
    case 'PROMOTIONAL': return 'danger'
    case 'WARM': return 'warning'
    case 'PROFESSIONAL': return 'info'
    default: return ''
  }
}

// 生命周期
onMounted(() => {
  // 检查路由参数
  const imageId = route.query.imageId
  const imageIds = route.query.imageIds
  
  if (imageIds) {
    // 批量生成模式
    const ids = (imageIds as string).split(',').map(id => parseInt(id))
    handleLoadImages().then(() => {
      batchImages.value = images.value.filter(img => ids.includes(img.id))
      if (batchImages.value.length > 0) {
        batchVisible.value = true
      }
    })
  } else if (imageId) {
    // 单个图片模式
    handleLoadImages().then(() => {
      const image = images.value.find(img => img.id === parseInt(imageId as string))
      if (image) {
        handleSelectImage(image)
      }
    })
  } else {
    handleLoadImages()
  }
})
</script>

<style scoped>
.generate-page {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.generate-header {
  text-align: center;
  margin-bottom: 40px;
}

.page-title {
  font-size: 2.5rem;
  font-weight: 700;
  color: white;
  margin: 0 0 15px 0;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
}

.page-description {
  font-size: 1.1rem;
  color: rgba(255, 255, 255, 0.8);
  margin: 0;
}

.generate-content {
  display: grid;
  grid-template-columns: 400px 1fr;
  gap: 30px;
}

.generate-sidebar {
  position: sticky;
  top: 20px;
}

.generate-main {
  display: flex;
  flex-direction: column;
  gap: 30px;
  min-width: 0;
}

/* 操作面板样式 */
.action-panel {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 20px;
  color: white;
}

.panel-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.panel-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.selected-text-preview {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 15px;
  padding: 20px;
  margin-bottom: 20px;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.preview-title {
  font-size: 14px;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.8);
}

.preview-meta {
  display: flex;
  gap: 8px;
}

.preview-content {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 10px;
  padding: 15px;
  line-height: 1.6;
  color: white;
}

.action-buttons {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

/* 批量生成样式 */
.batch-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.batch-images h4,
.batch-config h4 {
  margin: 0 0 15px 0;
  color: #333;
}

.batch-images-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
  gap: 10px;
  max-height: 200px;
  overflow-y: auto;
}

.batch-image-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.batch-image-item img {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 5px;
}

.batch-image-name {
  font-size: 10px;
  text-align: center;
  color: #666;
  word-break: break-all;
}

/* 批量进度样式 */
.batch-progress {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
}

.progress-details {
  max-height: 300px;
  overflow-y: auto;
}

.progress-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.progress-item.completed {
  color: #67c23a;
}

.progress-item.error {
  color: #f56c6c;
}

.progress-item .loading {
  animation: spin 1s linear infinite;
}

.error-text {
  font-size: 12px;
  color: #f56c6c;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .generate-content {
    grid-template-columns: 350px 1fr;
    gap: 20px;
  }
}

@media (max-width: 768px) {
  .generate-page {
    padding: 15px;
  }
  
  .generate-content {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .generate-sidebar {
    position: static;
  }
  
  .action-buttons {
    grid-template-columns: 1fr;
  }
}
</style>